<template>
<div class="drawSpaceBox">
  <!-- 搜索 -->
    <div class="searchBox">
      <div>
        <a-input placeholder="请输入关键字" :value="dataControl.searchValue" :id="inputID"></a-input>
        <span class="iconfont">&#xe7ba;</span>
      </div>
      <div class="right">
        <div v-if="dataControl.cont">
          <a-input placeholder="请输入围栏名字" v-model="dataControl.spaceName" style="width: 120px"></a-input>
          <a-select style="width: 107px" v-model="dataControl.spaceType"  @change="drawSpaceChange($event,dataControl.uuid)">
            <a-select-option v-for="item in dataControl.spaceList" :key="item.type">
              {{ item.title}}
              
            </a-select-option>
          </a-select>
        </div>
        <p v-else>
          {{ dataControl.spaceName}}
          
        </p>
      </div>
    </div>
    <div :id="drawSpaceId" style="width: 100%; height: 100%"></div>
  </div>
</template>

<script>
export default {
  props:['dataControl','lookKey'],
    data() {
        return {
          drawSpaceId:`drawSpace${Math.random()}`.replace(".",''),
					inputID:`drawSpaceV2${Math.random()+new Date().getTime()}`.replace(".",''),
          map: null, //地图实例
          mouseTool: null, //绘图插件
          overlays: [], //矢量图集合
          overlaysPol: [],
          editCircle: null, //编辑圆形实例
          editPol: null, //编辑多边形实例
          spaceName: '',
          cicleInfo: {
            //编辑的圆的信息
            center: [],
            radius: '',
          },
          polygonInfo: [],
          circleEditor: null,
          editPolDraw: null,
          polygons: [],
        }
    },
    mounted(){
       const that=this;
			 this.dropSpaceLoad().then(()=>{
        that.drawSpaceInitMap()
			})
    },
    methods: {
			dropSpaceLoad () {
				return new Promise((resolve, reject) => {
          const id = ('drawSpace' + (Math.random()* new Date().getTime())).replace('.','')
					if (window.AMap) {
						resolve(window.AMap)
					} else {
						var url = `https://webapi.amap.com/maps?v=1.4.15&key=48b318ebd182d7a08de1431c42d849ed&callback=onLoad${id}`
						var script = document.createElement('script')
						script.charset = 'utf-8'
						script.src = url
						script.onerror = reject
						document.head.appendChild(script)
					}
					window[`onLoad${id}`] = () => {
						resolve(window.AMap)
					}
				})
			},
      drawSpaceInitMap() {
			let that = this;
					this.map = new AMap.Map(this.drawSpaceId, {
					center: [116.39, 39.9],
					enableHighAccuracy: true, 
					convert: true, 
					timeout: 10000 
					});
            //搜索
            AMap.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch'], function () {
               //异步加载插件
               var autoOptions = {
                  input: that.inputID
               };
               var auto = new AMap.Autocomplete(autoOptions);
               var placeSearch = new AMap.PlaceSearch({
                  map:that.map
               });
               //构造地点查询类
               AMap.event.addListener(auto, 'select', select); //注册监听，当选中某条记录时会触发
               function select(e) {
                  placeSearch.setCity(e.poi.adcode);
                  placeSearch.search(e.poi.name); //关键字查询查询
               }
            });

            AMap.plugin('AMap.MouseTool', function () {
               that.mouseTool = new AMap.MouseTool(that.map);
            });
            
            // 数据源
            
		},
    drawSpaceChange(v,id) {
			if (this.circleEditor)  this.circleEditor.close();
			if (this.editPolDraw)  this.editPolDraw.close();
			this.map.remove(this.overlays);
			this.map.remove(this.overlaysPol);
			if (this.editCircle) {
				this.map.remove(this.editCircle);
			}
			if (this.editPol) {
				this.map.remove(this.editPol);
			}
			if (this.polygons) {
				this.map.remove(this.polygons); //清除上次结果
			}
			this.mouseTool.close(true);
			switch (v) {
				case 'circle':
					this.drawSpaceCircle(id);
					break;
				case 'polygon':
					this.drawSpacePolygon(id);
					break;
				case 'district':
					this.drawSpaceDistrict({id});
					break;
				case '重新绘制':
					return '';
			}
		},
      	//绘制圆形
		drawSpaceCircle(id) {
			this.map.remove(this.overlays);
			this.mouseTool.close(true);
			this.mouseTool.circle({
				strokeColor: '#1791fc',
				strokeOpacity: 1,
				strokeWeight: 1,
				fillColor: '#1791fc',
				fillOpacity: 0.4,
				strokeStyle: 'solid'
				// 线样式还支持 'dashed'
				// strokeDasharray: [30,10],
			});
			this.mouseTool.on('draw', event => {
				if (this.dataControl.spaceType === 'circle') {
					let center = [event.obj.w.center.lng, event.obj.w.center.lat];
					let borderLnglat = [event.obj.getPath()[0].lng, event.obj.getPath()[0].lat];
					// 返回 p1 到 p2 间的地面距离，单位：米
					var circleLength = AMap.GeometryUtil.distance(center, borderLnglat);
					this.drawSpaceEdit(center, circleLength,id);
					this.map.remove(this.overlays);
					this.overlays.push(event.obj);
					this.mouseTool.close(true);
					if (circleLength > 50000) {
						this.circleEditor.close();
						this.map.remove(this.overlays);
						this.map.remove(this.editCircle);
						this.dataControl.spaceType = '重新绘制';
						this.$message.error('目前支持最大范围在50000米及以内');
						return;
					}
            this.drawSpaceSaveData({
						type: 'circle',
						center: `${center[0]},${center[1]}`,
						radius: circleLength,
                  id
					});
				   this.dataControl.spaceType = '重新绘制';
				}
			});
		},
       //编辑圆形
		drawSpaceEdit(center, circleLength,id) {
			const that = this;
			this.editCircle = new AMap.Circle({
				center,
				radius: circleLength, //半径
				strokeColor: '#1791fc',
				strokeOpacity: 1,
				strokeWeight: 1,
				fillColor: '#1791fc',
				fillOpacity: 0.4,
				strokeStyle: 'solid',
				zIndex: 50
			});
			this.editCircle.setMap(this.map);
			AMap.plugin('AMap.CircleEditor', () => {
				that.circleEditor = new AMap.CircleEditor(that.map, that.editCircle);
				that.circleEditor.open();
				that.circleEditor.on('adjust', e => {
					if (e.radius > 50000) {
						that.cicleInfo = {
							center,
							radius: 50000
						};
						that.circleEditor.close();
						that.map.remove(that.overlays);
						that.map.remove(that.editCircle);
						that.dataControl.spaceType = '重新绘制';
						that.$message.error('目前仅支持50000以以内的范围');
						// that.cicleInfo = {...that.cicleInfo, center, radius: e.radius};
						return;
					}
					that.cicleInfo = {...that.cicleInfo, center, radius: e.radius};
                 that.drawSpaceSaveData({
                  ...that.cicleInfo,
                  id
					});
				});
				that.circleEditor.on('move', e => {
					that.cicleInfo = {...that.cicleInfo, center: [e.lnglat.lng, e.lnglat.lat]};
					// that.circleEditor.close();
                 that.drawSpaceSaveData({
                  ...that.cicleInfo,
                  id
					});
				});
			});
		},
      //绘制多边形
		drawSpacePolygon(id) {
         const that = this;
			this.map.remove(this.overlaysPol);
			this.mouseTool.close(true);
			this.mouseTool.polygon({
				strokeColor: '#1791fc',
				strokeOpacity: 1,
				strokeWeight: 1,
				fillColor: '#1791fc',
				fillOpacity: 0.4,
				// 线样式还支持 'dashed'
				strokeStyle: 'solid'
				// strokeStyle是dashed时有效
				// strokeDasharray: [30,10],
			});
			this.mouseTool.on('draw', event => {
				if (that.dataControl.spaceType === 'polygon') {
					that.mouseTool.close();
					that.overlaysPol.push(event.obj);
					let arr = [];
					event.obj.w.path.forEach(item => {
						arr.push(JSON.stringify([item.lng, item.lat]));
					});
					that.drawSpaceEditPolygon(id,arr);
					that.map.remove(that.overlaysPol);
					that.overlays.push(event.obj);
            that.drawSpaceSaveData({
						type: 'polygon',
						points: event.obj
							.getPath()
							.map(item => [item.lng, item.lat])
							.join(';'),
                  id
					});
					that.dataControl.spaceType = '重新绘制';
				}
			});
		},

      //编辑多边形
      drawSpaceEditPolygon(id,poins, type) {
			let list = [];
			if (type) {
				list = poins;
			} else {
				poins.forEach(item => {
					list.push(JSON.parse(item));
				});
			}
			const that = this;
			this.editPol = new AMap.Polygon({
				path: list,
				strokeColor: '#1791fc',
				strokeOpacity: 1,
				strokeWeight: 1,
				fillColor: '#1791fc',
				fillOpacity: 0.4,
				strokeStyle: 'solid',
				zIndex: 50
			});
			this.editPol.setMap(this.map);
			this.map.setFitView([this.editPol]);
			AMap.plugin('AMap.PolyEditor', () => {
				that.editPolDraw = new AMap.PolyEditor(that.map, that.editPol);
				that.editPolDraw.open();
				that.editPolDraw.on('adjust', e => {
					that.polygonInfo = e.target.w.path;
					const arr = e.target.w.path.map(item => [item.lng, item.lat]).join(';');
					that.drawSpaceSaveData({points: arr, type: 'polygon',id});
				});
			});
		},
      drawSpaceSaveData({center, name, radius, points, adcode, type,id}) {
			const value={
				label: id,
				value: {
					type,
					name: this.spaceName,
					center,
					radius,
					points,
					adcode
				}
			};
      this.$emit('input',value)
		},
      //行政区
      drawSpaceDistrict({id,adcode}) {
			const that = this;
			this.map.on('click', e => {
				if (that.dataControl.spaceType === 'district') {
					that.map.remove(that.polygons); //清除上次结果
					AMap.plugin(['AMap.Geocoder', 'AMap.DistrictSearch'], function () {
						let geocoder = new AMap.Geocoder();
						let district = new AMap.DistrictSearch({
							// 返回行政区边界坐标等具体信息
							extensions: 'all',
							// 设置查询行政区级别为 区
							level: 'district'
						});
						//查询点击位置坐标信息
						geocoder.getAddress([e.lnglat.lng, e.lnglat.lat], (status, result) => {
							if (status === 'complete' && result.regeocode) {
								district.search(result.regeocode.addressComponent.adcode, function (sta, res) {
									var bounds = res.districtList[0].boundaries;
									if (bounds) {
										for (var i = 0, l = bounds.length; i < l; i++) {
											//生成行政区划polygon
											var polygon = new AMap.Polygon({
												map: that.map,
												strokeWeight: 1,
												path: bounds[i],
												fillOpacity: 0.7,
												fillColor: '#CCF3FF',
												strokeColor: '#CC66CC'
											});
											that.polygons.push(polygon);
										}
										// 地图自适应
										that.drawSpaceSaveData({
											type: 'district',
											adcode: result.regeocode.addressComponent.adcode,
                      id
										});
										that.map.setFitView();
									}
								});
							}
						});
					});
				}
			});
			if (adcode) {
				AMap.plugin(['AMap.Geocoder', 'AMap.DistrictSearch'], function () {
					let geocoder = new AMap.Geocoder();
					let district = new AMap.DistrictSearch({
						// 返回行政区边界坐标等具体信息
						extensions: 'all',
						// 设置查询行政区级别为 区
						level: 'district'
					});
					//查询点击位置坐标信息

					district.search(adcode, function (sta, res) {
						var bounds = res.districtList[0].boundaries;
						if (bounds) {
							for (var i = 0, l = bounds.length; i < l; i++) {
								//生成行政区划polygon
								var polygon = new AMap.Polygon({
									map: that.map,
									strokeWeight: 1,
									path: bounds[i],
									fillOpacity: 0.7,
									fillColor: '#CCF3FF',
									strokeColor: '#CC66CC'
								});
								that.polygons.push(polygon);
							}
							// 地图自适应
							that.drawSpaceSaveData({
								type: 'district',
								adcode: adcode,
                id
							});
							that.map.setFitView();
						}
					});
				});
			}
		},
    },
}
</script>
<style scoped lang="less">
.drawSpaceBox{
	width: 100%;
	height: 100%;
}
</style>